package com.bean;

import org.reflections.Reflections;

import java.util.HashSet;
import java.util.Set;

public class ClassUtil {

    /**
     * Gets sub types of * 获取类的所有实现类
     *
     * @param <T>    parameter
     * @param tClass t class
     * @return the sub types of
     */
    public static <T> Set<T> getSubTypesOf(Class<T> tClass) {
        // 扫描所有路径
        Reflections reflections = new Reflections();
        Set<Class<? extends T>> subTypesClass = reflections.getSubTypesOf(tClass);

        Set<T> subTypes = new HashSet<>();
        for (Class<? extends T> subType :
                subTypesClass) {
            try {
                T instance = subType.newInstance();
                subTypes.add(instance);
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return subTypes;
    }

    public static <T> Set<T> getSubTypesOf(Class<T> tClass, String prifix) {
        // 扫描所有路径
        Reflections reflections = new Reflections(prifix);
        Set<Class<? extends T>> subTypesClass = reflections.getSubTypesOf(tClass);

        Set<T> subTypes = new HashSet<>();
        for (Class<? extends T> subType :
                subTypesClass) {
            try {
                T instance = subType.newInstance();
                subTypes.add(instance);
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return subTypes;
    }

}
